# -*- coding: utf-8 -*-
import sys
import json
from typing import Optional

from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QLabel, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem,
                             QComboBox, QMessageBox, QHeaderView, QDialog, QDialogButtonBox)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from db_manager import DBManager

class User:
    def __init__(self, username: str, password: str, role: str):
        self.username = username
        self.password = password
        self.role = role

class UserManager:
    def __init__(self):
        self.db = DBManager()

    def get_all_users(self) -> list:
        """从数据库获取所有用户"""
        return [
            {"username": user[0], "password": user[1], "role": user[2]}
            for user in self.db.get_all_users()
        ]

    def add_user(self, username: str, password: str, role: str) -> bool:
        """添加用户到数据库"""
        return self.db.add_user(username, password, role)

    def update_user(self, old_username: str, new_username: str,
                   new_password: str, new_role: str) -> bool:
        """更新数据库用户信息"""
        return self.db.update_user(old_username, new_username, new_password, new_role)

    def delete_user(self, username: str) -> bool:
        """从数据库删除用户"""
        return self.db.delete_user(username)

    def user_exists(self, username: str) -> bool:
        """检查用户是否存在"""
        return self.db.user_exists(username)


class AddUserDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("添加新用户")
        self.setWindowIcon(QIcon.fromTheme('list-add'))

        layout = QVBoxLayout()
        self.setLayout(layout)

        # Username
        self.username_label = QLabel("用户名:")
        self.username_input = QLineEdit()
        layout.addWidget(self.username_label)
        layout.addWidget(self.username_input)

        # Password
        self.password_label = QLabel("密码:")
        self.password_input = QLineEdit()
        self.password_input.setEchoMode(QLineEdit.Password)

        # Show password button
        self.show_password_btn = QPushButton("显示")
        self.show_password_btn.setIcon(QIcon.fromTheme('visibility'))
        self.show_password_btn.setCheckable(True)
        self.show_password_btn.toggled.connect(self.toggle_password_visibility)

        password_layout = QHBoxLayout()
        password_layout.addWidget(self.password_input)
        password_layout.addWidget(self.show_password_btn)

        layout.addWidget(self.password_label)
        layout.addLayout(password_layout)

        # Role
        self.role_label = QLabel("权限:")
        self.role_combo = QComboBox()
        self.role_combo.addItems(["管理员", "普通用户"])
        layout.addWidget(self.role_label)
        layout.addWidget(self.role_combo)

        # Buttons
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

    def toggle_password_visibility(self, checked):
        if checked:
            self.password_input.setEchoMode(QLineEdit.Normal)
            self.show_password_btn.setText("隐藏")
            self.show_password_btn.setIcon(QIcon.fromTheme('visibility-off'))
        else:
            self.password_input.setEchoMode(QLineEdit.Password)
            self.show_password_btn.setText("显示")
            self.show_password_btn.setIcon(QIcon.fromTheme('visibility'))

    def get_user_data(self):
        return {
            'username': self.username_input.text().strip(),
            'password': self.password_input.text().strip(),
            'role': self.role_combo.currentText()
        }


class EditUserDialog(AddUserDialog):
    def __init__(self, user, parent=None):
        super().__init__(parent)
        self.setWindowTitle("编辑用户")
        self.setWindowIcon(QIcon.fromTheme('document-edit'))

        # Populate with existing user data
        self.username_input.setText(user["username"])
        self.password_input.setText(user["password"])
        index = self.role_combo.findText(user["role"])
        if index >= 0:
            self.role_combo.setCurrentIndex(index)


class UserManagementApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.user_manager = UserManager()  # 使用数据库管理
        self.init_ui()
        # 设置窗口的默认大小
        self.setGeometry(100, 100, 800, 600)

    def init_ui(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        # 设置窗口标题
        self.setWindowTitle("FTP服务用户管理")

        layout = QVBoxLayout()

        # Buttons
        button_layout = QHBoxLayout()
        add_button = QPushButton("添加用户")
        add_button.clicked.connect(self.show_add_user_dialog)
        edit_button = QPushButton("编辑用户")
        edit_button.clicked.connect(self.edit_user)
        delete_button = QPushButton("删除用户")
        delete_button.clicked.connect(self.delete_user)

        button_layout.addWidget(add_button)
        button_layout.addWidget(edit_button)
        button_layout.addWidget(delete_button)

        layout.addLayout(button_layout)

        # User table
        self.user_table = QTableWidget()
        self.user_table.setColumnCount(4)
        self.user_table.setHorizontalHeaderLabels(["用户名", "密码", "权限", "操作"])
        self.user_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # 设置表格为不可编辑
        self.user_table.setEditTriggers(QTableWidget.NoEditTriggers)
        layout.addWidget(self.user_table)

        central_widget.setLayout(layout)

        self.load_users()

    def load_users(self):
        """从数据库加载用户到表格"""
        users = self.user_manager.get_all_users()
        self.user_table.setRowCount(len(users))

        for row, user in enumerate(users):
            # 用户名
            username_item = QTableWidgetItem(user["username"])
            self.user_table.setItem(row, 0, username_item)

            # 密码（默认隐藏）
            password_item = QTableWidgetItem("*" * 8)
            password_item.setData(Qt.UserRole, user["password"])  # 存储真实密码
            self.user_table.setItem(row, 1, password_item)

            # 角色
            role_item = QTableWidgetItem(user["role"])
            self.user_table.setItem(row, 2, role_item)

            # 显示密码按钮
            show_pw_btn = QPushButton("显示密码")
            show_pw_btn.setCheckable(True)
            show_pw_btn.toggled.connect(
                lambda checked, r=row: self.toggle_password_visibility(r, checked)
            )
            self.user_table.setCellWidget(row, 3, show_pw_btn)

    def toggle_password_visibility(self, row: int, checked: bool):
        """切换密码显示"""
        password_item = self.user_table.item(row, 1)
        if checked:
            password_item.setText(password_item.data(Qt.UserRole))
        else:
            password_item.setText("*" * 8)

    def show_add_user_dialog(self):
        """添加用户对话框"""
        dialog = AddUserDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            user_data = dialog.get_user_data()
            if not all(user_data.values()):
                QMessageBox.warning(self, "错误", "所有字段必须填写！")
                return

            if self.user_manager.add_user(user_data["username"], user_data["password"], user_data["role"]):
                QMessageBox.information(self, "成功", "用户添加成功！")
                self.load_users()
            else:
                QMessageBox.warning(self, "错误", "用户名已存在！")

    def edit_user(self):
        """编辑用户"""
        selected_user = self.get_selected_user()
        if not selected_user:
            return

        dialog = EditUserDialog(selected_user, self)
        if dialog.exec_() == QDialog.Accepted:
            new_data = dialog.get_user_data()
            if not all(new_data.values()):
                QMessageBox.warning(self, "错误", "所有字段必须填写！")
                return

            if self.user_manager.update_user(
                selected_user["username"],
                new_data["username"],
                new_data["password"],
                new_data["role"]
            ):
                QMessageBox.information(self, "成功", "用户信息已更新！")
                self.load_users()
            else:
                QMessageBox.warning(self, "错误", "更新失败，用户名可能已存在！")

    def delete_user(self):
        """删除用户"""
        selected_user = self.get_selected_user()
        if not selected_user:
            return

        reply = QMessageBox.question(
            self, "确认删除",
            f"确定要删除用户 '{selected_user['username']}' 吗？",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            if self.user_manager.delete_user(selected_user["username"]):
                QMessageBox.information(self, "成功", "用户已删除！")
                self.load_users()
            else:
                QMessageBox.warning(self, "错误", "删除失败！")

    def get_selected_user(self) -> Optional[dict]:
        """获取当前选中的用户"""
        selected_rows = self.user_table.selectionModel().selectedRows()
        if not selected_rows:
            QMessageBox.warning(self, "警告", "请先选择一个用户！")
            return None
        row = selected_rows[0].row()
        username = self.user_table.item(row, 0).text()
        users = self.user_manager.get_all_users()
        return next((u for u in users if u["username"] == username), None)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = UserManagementApp()
    window.show()
    sys.exit(app.exec_())